<template>
  <div class="page">
    <div class="title-wrap">
      <h3 class="sub-title success-color">3列提数</h3>
    </div>
    <div class="cont">
      <div class="input-wrap">
        <el-input
          v-model="inputValue"
          type="textarea"
          placeholder="请输入数字"
          :autosize="{ minRows: 6, maxRows: 20 }"
        />
      </div>
      <div class="form-item">
        <div class="label">每轮统计行数：</div>
        <div class="value">
          <el-input
            v-model="rowCount"
            placeholder="比如：5"
            @change="rowCountChange"
            style="width: 120px"
          />
        </div>
      </div>
      <!-- <div class="form-item">
        <div class="label">
          对输入排序：
        </div>
        <div class="value">
          <el-radio-group v-model="sortType">
            <el-radio label="1" size="large">从小到大</el-radio>
            <el-radio label="2" size="large">从大到小</el-radio>
            <el-radio label="3" size="large">不排序</el-radio>
          </el-radio-group>
        </div>
      </div> -->
      <!-- <div class="form-item">
        <div class="label">
          每组数字个数：
        </div>
        <div class="value">
          <el-input
            v-model="mapSize"
            placeholder="比如：6"
            @change="mapSizeChange"
          />
        </div>
      </div> -->

      <!-- <div class="form-item">
        <div class="label">
          是否复式拆解：
        </div>
        <div class="value">
          <el-radio-group v-model="fushi">
            <el-radio label="0" size="large">否</el-radio>
            <el-radio label="1" size="large">是</el-radio>
          </el-radio-group>
        </div>
      </div> -->

      <div class="btn-group">
        <el-button type="primary" @click="startComputed"
          >ok/ctrl+enter</el-button
        >
      </div>

      <div
        class="result-wrap"
        v-if="finalResult  && showComputedResult"
      >
        <div class="title">
          结果:
          <el-button type="primary" @click="copyFinalResult">复制</el-button>
          <el-button type="primary" @click="downloadFile">下载</el-button>
          <!-- <el-button type="primary" @click="copySortGroupDanCiListRows"
            >复制(多行)</el-button
          > -->
          <!-- <span class="link-btn" @click="downloadExcel">下载表格结果</span> -->
        </div>
        <div class="total">共{{ totalNum }}组</div>
        <div class="result-list-wrap" v-for="(ciList, index) in finalResult"
            :key="index">
          <div class="result-list-row">
            <div class="name">第{{ index + 1 }}轮：</div>
            <div
              class="result-item"
              v-for="(ciItem, ciIndex) in ciList"
              :key="ciIndex"
            >
              <div class="res-label">
                【{{ ciItem.cishu }}次】({{ ciItem.nums.length }}个)：
              </div>

              <div class="res-value">
                {{ ciItem.nums.join(' ') }}
              </div>
            </div>
          </div>
        
        </div>
      </div>
    </div>
    <textarea
      id="copyTextArea"
      class="mf-area"
      ref="copyTextAreaRef"
      name=""
      cols="30"
      value=""
      rows="10"
    ></textarea>
  </div>
</template>

<script>
import { splitCharOptions } from '@/utils/constant'
import { ElMessage } from 'element-plus'
import {
  downFile,
  numToString,
  chineseNumToNumber,
  deepCopy
} from '../utils/tools'
import { isReqOverflow } from '../utils/userLimit'
import * as XLSX from 'xlsx-js-style'
import { adminDialog } from '@/components/adminDialog'
import { getUserInfo } from '@/utils/auth.js'
import { request } from '@/api/fetch'

// let todayInputSplitResultHistorykey = getShortTodayStr() + '/inputSplitResultHistory'
let mapSizeStorageKey = 'mapSize'
let userInfo = getUserInfo()
const splitReg = /[\s,，;；、.。；;\n\-_\t\\\/\?？\+]+/
let rowCountStorageKey = 'rowCount'
export default {
  data() {
    return {
      inputValue: ``,
      sortType: '1', // 1 从小到大排，2从大到小排，3 不排序
      mapSize: localStorage.getItem(mapSizeStorageKey) || '6',
      splitCharOptions: splitCharOptions,
      finalResult: null,
      showComputedResult: false,
      fushi: '0', // 是否复式拆解,
      totalNum: 0,
      rowCount: localStorage.getItem(rowCountStorageKey) || '5',
      countType:'2'
    }
  },

  methods: {
    setResultText(str) {
      // console.log('copyTextAreaRef.value:',copyTextAreaRef.value)
      this.$refs.copyTextAreaRef.value = str
    },
    rowCountChange(value) {
      // console.log('value:',value)
      localStorage.setItem(rowCountStorageKey, value)
    },
    copyResultText() {
      this.$refs.copyTextAreaRef.select()
      document.execCommand('copy')
      ElMessage.closeAll()
      ElMessage({
        type: 'success',
        message: '复制成功',
        duration: 5000
      })
    },
    getDownloadStr() {
      let str = ''
      this.finalResult.forEach((ciList, index) => {
        str += `第${index + 1}轮：\n`
        ciList.forEach((ciItem, ciIndex) => {
          str += `【${ciItem.cishu}次】(${ciItem.nums.length}个)：${ciItem.nums.join(
            ' '
          )}\n`
        })
        str += '\n'
        
      })
      return str
    },

    copyFinalResult() {
      let str = this.getDownloadStr()

      this.setResultText(str)
      this.copyResultText()
    },
    downloadFile() {
      // 超出免费限制
      // 超出免费限制
      // if (isReqOverflow()) {
      //   adminDialog.show()
      //   return
      // }
      let str = this.getDownloadStr()
      let blob = new Blob([str], { type: 'text/plain;charset=utf-8' })
      downFile('结果_.txt', blob)
    },

    mapSizeChange(value) {
      // console.log('value:',value)
      localStorage.setItem(mapSizeStorageKey, value)
    },
    getNumFrom3List(list1, list2, list3) {
      let result = []
      if (
        Array.isArray(list1) &&
        Array.isArray(list2) &&
        Array.isArray(list3)
      ) {
        list1.forEach((item1) => {
          list2.forEach((item2) => {
            list3.forEach((item3) => {
              result.push(item1 + item2 + item3)
            })
          })
        })
      }
      return result
    },

    startComputed() {
      this.showComputedResult = false
      if (!this.inputValue.trim()) {
        ElMessage.closeAll()
        ElMessage.error('请输入数字')
        return
      }
      if (!/^\d+$/.test(this.rowCount) || Number(this.rowCount) <= 0) {
        ElMessage.closeAll()
        ElMessage.error('统计行数必须为数字且大于0')
        return
      }
      let inputNumList = this.inputValue.trim().split(/\n/)

      let inputAoaNumList = inputNumList.map((row, index) => {
        return row.trim().split(/\s+/)
      })
      console.log('inputAoaNumList:', inputAoaNumList)
      let hasError = -1
      // [['1,2,3','4,5,6','7,8,9'],[]]
      inputAoaNumList.some((row, index) => {
        if (row.length !== 3) {
          hasError = index
          return
        }
        row.forEach((colItem) => {
          colItem.split(splitReg).forEach((item) => {
            if (!/^\d+$/.test(item)) {
              hasError = index
              return
            }
          })
        })
      })
      if (hasError > -1) {
        ElMessage.closeAll()
        ElMessage.error('第' + (Number(hasError) + 1) + '行，数据存在错误，请检查')
        return
      }
      if (isReqOverflow()) {
        adminDialog.show()
        return
      }

      let totalNumAoaResult = []
      inputNumList.forEach((rowStr) => {
        
        // columns ['1,2,3','4,5,6','7,8,9]
        let columns = rowStr.trim().split(/\s+/)
        // aoaColumns [[1,2,3],[4,5,6],[7,8,9]]
        let aoaColumns = columns.map((item) => {
          return item.split(splitReg)
        })
        // numsList [147,148,149]
        let rowNumList = this.getNumFrom3List(
          aoaColumns[0],
          aoaColumns[1],
          aoaColumns[2]
        )
        // totalNumAoaResult = [[123,456,789]]
        totalNumAoaResult.push(rowNumList)
        // tempResult = tempResult.concat(numsList)
      })
      let totalNum = 0
      totalNumAoaResult.forEach((rowNumList) => {
        totalNum += rowNumList.length
      })
      this.totalNum = totalNum
      // console.log('tempResult:', tempResult)
      // groupList [[123,456,789],[123,456,789]],其中每一项为1-m行数据结果汇总
      let groupList = [] 
      let rowCount = Number(this.rowCount)
      // 滚动统计
      if (this.countType === '2') {
        for (let i = 0; i + rowCount <= totalNumAoaResult.length; i++) {
          let tempArr = totalNumAoaResult.slice(i, i + rowCount)
          tempArr = tempArr.flat()
          groupList.push(tempArr)
        }
      }
      
      
      let finalResult = groupList.map((group) => {
        // 获取出现0次的数字
        let allNumList  = group.flat()
        let zeroNumList = []
        for(let i=0;i<999;i++){
          // 将数字转成字符串，且长度补成3位数
          let strNum = numToString(i, 3)
          if(!allNumList.includes(strNum)){
            zeroNumList.push(strNum)
          }
        }
        // 统计每个数出现的次数
        let map = new Map()
        group.forEach((item) => {
          if (map.has(item)) {
            map.set(item, map.get(item) + 1)
          } else {
            map.set(item, 1)
          }
        })
        let numsObj = {}
        map.forEach((cishu, num) => {
          if (numsObj[cishu]) {
            numsObj[cishu].push(num)
          } else {
            numsObj[cishu] = [num]
          }
        })
        numsObj[0] = zeroNumList
        return Object.keys(numsObj)
        .sort((a,b)=>{
          return Number(b) - Number(a)
        })
        .map((key) => {
          return {
            cishu: key,
            nums: numsObj[key].sort()
          }
        })
      })
      

      
      console.log('finalResult:', finalResult)

      this.finalResult = finalResult
      this.showComputedResult = true
      // loadingInstance.close()
      // console.log('this.finalResult:',this.finalResult)
      // console.log('this.showComputedResult:',this.showComputedResult)
    },
    generateFuShi(nums) {
      const result = []
      function backtrack(current, remaining) {
        if (remaining.length === 0) {
          result.push([...current])
          return
        }
        for (let i = 0; i < remaining.length; i++) {
          const nextNum = remaining[i]
          current.push(nextNum)
          const newRemaining = [
            ...remaining.slice(0, i),
            ...remaining.slice(i + 1)
          ]
          backtrack(current, newRemaining)
          current.pop()
        }
      }
      backtrack([], nums)
      return result
    },
    getCombinations(arr, m) {
      if (m < 0 || m > arr.length) {
        throw new Error(`m 必须在 0 到 ${arr.length} 之间`)
      }

      const result = []

      // 回溯函数
      function backtrack(start, current) {
        if (current.length === m) {
          result.push([...current])
          return
        }

        for (let i = start; i < arr.length; i++) {
          current.push(arr[i])
          backtrack(i + 1, current)
          current.pop() // 回溯
        }
      }

      backtrack(0, [])
      return result
    },

    downloadExcel() {
      // 超出免费限制
      // 超出免费限制
      // if (isReqOverflow()) {
      //   adminDialog.show()
      //   return
      // }
      let wb = XLSX.utils.book_new()
      // groupResult [{num:1,valueStr:'1',valueList:['1']}]
      let finalResult = this.finalResult
      let colNum = 0

      let excelAoa = []
      let header = ['号码', '出现次数']

      excelAoa.push(header)
      finalResult.forEach((item) => {
        let row = [item.number, item.times]
        excelAoa.push(row)
      })
      let excelWorkSheet = XLSX.utils.aoa_to_sheet(excelAoa)
      XLSX.utils.book_append_sheet(wb, excelWorkSheet, '统计结果')
      let abuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
      let blob = new Blob([abuffer], { type: 'application/octet-stream' })
      downFile('统计结果.xlsx', blob)
    }
  },
  async created() {
    userInfo = getUserInfo()
    // 获取次数统计结果
    // 获取为单为组的不同的数字个数
  },
  mounted() {
    document.addEventListener('keydown', this.globalEnterEvent)
  },
  beforeDestroy() {
    document.removeEventListener('keydown', this.globalEnterEvent)
  }
}
</script>

<style lang="scss" scoped>

.mf-area {
  position: absolute;
  top: -10000px;
  left: 0px;
  width: 100%;
  height: 0px;
  border: none;
  outline: none;
}

.cont {
  margin: auto;
  // max-width: 600px;
  border-radius: 4px;
  padding: 20px;
  padding-bottom: 60px;
  box-sizing: border-box;
  background: rgba(17, 150, 219, 0.1);
  overflow-x: hidden;

  .input-wrap {
    margin-top: 20px;
  }
  .form-item {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-top: 16px;
  }

  .btn-group {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
.result-wrap {
  // background-color: #f5f5f5;

  .title {
    margin-top: 32px;
    font-weight: bold;
    .link-btn {
      margin-left: 20px;
      text-decoration: underline;
      cursor: pointer;
      color: blue;
    }
  }
  .total {
    margin-top: 20px;
  }
  .total-group {
    margin-top: 20px;
  }
  .tools-wrap {
    margin-top: 20px;
    display: flex;
    align-items: center;
    justify-content: flex-start;
  }
  .result-list-wrap {
    margin-top: 20px;
    
    
    box-sizing: border-box;
    border-radius: 4px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    .result-list-row{
      background-color: #f5f5f5;
      padding: 10px 10px 20px;
      .name{
        color:red
      }
    }
   
  }
  .result-list-wrap-noflex {
    margin-top: 20px;
    background-color: #f5f5f5;
    padding: 10px 10px 20px;
    box-sizing: border-box;
    border-radius: 4px;
    .result-item {
      margin-top: 20px;
      .label {
        width: 120px;
      }
    }
  }
  .no-result {
    background-color: #f5f5f5;
    padding: 10px 10px 20px;
    margin-top: 20px;
    color: red;
    text-align: center;
  }
  .times-result-item {
    margin-top: 20px;
    .item {
      display: flex;
      align-items: flex-start;
      margin-top: 4px;
      .label {
        flex-shrink: 0;
        word-break: keep-all;
        width: 60px;
        flex-shrink: 0;
      }
    }
  }
  .result-item {
    word-break: break-all;
    margin-top: 20px;

    .res-label {
      flex-shrink: 0;
      word-break: keep-all;
      flex-shrink: 0;
      margin-bottom: 10px;
    }
    .res-value {
      margin-left: 10px;
      // color: red;
      word-break: break-word;
    }
  }
}
</style>
